using UnityEngine;
using UnityEngine.UI;
using TMPro;
using System;
using System.Collections.Generic;
using UI.BankingPanel.Data;

namespace UI.BankingPanel.Components
{
    /// <summary>
    /// 押注数据字段类型枚举
    /// </summary>
    public enum BetDataFieldType
    {
        TotalBet,   // 总押注
        EatCode,    // 吃码
        Report      // 上报
    }

    /// <summary>
    /// 押注数据列表项组件
    /// 负责显示单个列表项中的多个号码押注数据（通常4个号码）
    /// 
    /// 主要功能：
    /// 1. 显示4个号码的押注数据（号码、总押注、自己吃码、上报数）
    /// 2. 提供输入框供用户编辑押注数据
    /// 3. 自动计算上报数量（总数 - 自己吃码）
    /// 4. 实时响应数据变化并通知上层组件
    /// 5. 支持显示/隐藏无效数据行
    /// 6. 支持本命年特殊显示和数据输入
    /// 
    /// 数据流：
    /// 用户输入 -> 数据验证 -> 更新本地数据 -> 触发回调 -> 更新显示
    /// </summary>
    public class C_Bet_ScrollViewItem : MonoBehaviour
    {
        [Header("数据行组件")]
        [SerializeField] private List<NumberDataRow> m_DataRows = new List<NumberDataRow>();
        
        [Header("名称显示")]
        [SerializeField] private TextMeshProUGUI m_SpecificNameText;
        
        // 数据相关
        private List<NumberBetData> m_ItemData;
        private int m_StartIndex;
        private Action<int, BetDataFieldType, float> m_OnBetDataFieldChanged;
        
        // 组件状态
        private bool m_IsInitialized = false;
        
        // 系统更新标志位，用于区分用户输入和系统设置
        private bool m_IsSystemUpdating = false;
        
        /// <summary>
        /// 单个号码数据行结构
        /// </summary>
        [System.Serializable]
        public class NumberDataRow
        {
            [Header("号码显示")]
            public TextMeshProUGUI numberText;
            
            [Header("输入框")]
            public TMP_InputField totalBetInput;
            public TMP_InputField eatCodeInput;
            public TMP_InputField reportInput;
            
            [Header("背景")]
            public GameObject numberBackground;
            public GameObject totalBetBackground;
            public GameObject eatCodeBackground;
            public GameObject reportBackground;
            
            // 数据索引
            [HideInInspector] public int dataIndex = -1;
        }
        
        #region 初始化方法
        
        /// <summary>
        /// 初始化列表项组件
        /// </summary>
        public void Initialize()
        {
            if (m_IsInitialized) 
            {
                Debug.Log("[C_Bet_ScrollViewItem] 已经初始化过了，跳过");
                return;
            }
            
            Debug.Log("[C_Bet_ScrollViewItem] 开始初始化...");
            
            // 自动查找组件
            FindComponents();
            
            // 初始化数据行
            InitializeDataRows();
            
            m_IsInitialized = true;
            Debug.Log($"[C_Bet_ScrollViewItem] 初始化完成，找到数据行数量: {m_DataRows.Count}");
        }
        
        /// <summary>
        /// 自动查找UI组件
        /// </summary>
        private void FindComponents()
        {
            // 查找名称文本
            if (m_SpecificNameText == null)
            {
                Transform nameNode = transform.Find("BetData_Content/Name_Info/Specific_Name_Node/Specific_Name");
                if (nameNode != null)
                {
                    m_SpecificNameText = nameNode.GetComponent<TextMeshProUGUI>();
                }
            }
            
            // 查找数据行组件
            if (m_DataRows.Count == 0)
            {
                FindDataRows();
            }
        }
        
        /// <summary>
        /// 查找数据行组件
        /// </summary>
        private void FindDataRows()
        {
            m_DataRows.Clear();
            
            // 查找4个数据行
            for (int i = 1; i <= 4; i++)
            {
                string numberInfoPath = $"BetData_Content/Number_Info_{i}/Data_Row_1";
                Transform rowTransform = transform.Find(numberInfoPath);
                
                if (rowTransform != null)
                {
                    NumberDataRow dataRow = CreateDataRowFromTransform(rowTransform);
                    if (dataRow != null)
                    {
                        m_DataRows.Add(dataRow);
                    }
                }
            }
        }
        
        /// <summary>
        /// 从Transform创建数据行对象
        /// </summary>
        /// <param name="rowTransform">行Transform</param>
        /// <returns>数据行对象</returns>
        private NumberDataRow CreateDataRowFromTransform(Transform rowTransform)
        {
            NumberDataRow dataRow = new NumberDataRow();
            
            // 查找号码文本
            Transform numberNode = rowTransform.Find("Number_Background/Number");
            if (numberNode != null)
            {
                dataRow.numberText = numberNode.GetComponent<TextMeshProUGUI>();
                dataRow.numberBackground = rowTransform.Find("Number_Background")?.gameObject;
            }
            
            // 查找总押注输入框
            Transform totalBetNode = rowTransform.Find("Total_Bet_Input_Background/Row1_Total_Bet_Input");
            if (totalBetNode != null)
            {
                dataRow.totalBetInput = totalBetNode.GetComponent<TMP_InputField>();
                dataRow.totalBetBackground = rowTransform.Find("Total_Bet_Input_Background")?.gameObject;
            }
            
            // 查找吃码输入框
            Transform eatCodeNode = rowTransform.Find("Eat_Code_Input_Background/Row1_Total_Bet_Input");
            if (eatCodeNode != null)
            {
                dataRow.eatCodeInput = eatCodeNode.GetComponent<TMP_InputField>();
                dataRow.eatCodeBackground = rowTransform.Find("Eat_Code_Input_Background")?.gameObject;
            }
            
            // 查找上报输入框
            Transform reportNode = rowTransform.Find("Report_Input_Background/Row1_Total_Bet_Input");
            if (reportNode != null)
            {
                dataRow.reportInput = reportNode.GetComponent<TMP_InputField>();
                dataRow.reportBackground = rowTransform.Find("Report_Input_Background")?.gameObject;
            }
            
            return dataRow;
        }
        
        /// <summary>
        /// 初始化数据行
        /// </summary>
        private void InitializeDataRows()
        {
            for (int i = 0; i < m_DataRows.Count; i++)
            {
                NumberDataRow dataRow = m_DataRows[i];
                
                // 绑定输入框事件
                BindInputFieldEvents(dataRow, i);
            }
        }
        
        /// <summary>
        /// 绑定输入框事件
        /// </summary>
        /// <param name="dataRow">数据行</param>
        /// <param name="rowIndex">行索引</param>
        private void BindInputFieldEvents(NumberDataRow dataRow, int rowIndex)
        {
            // 总押注输入框事件 - 使用onEndEdit避免输入过程中频繁刷新
            if (dataRow.totalBetInput != null)
            {
                dataRow.totalBetInput.onEndEdit.AddListener((value) => OnTotalBetChanged(rowIndex, value));
            }
            
            // 吃码输入框事件 - 使用onEndEdit避免输入过程中频繁刷新
            if (dataRow.eatCodeInput != null)
            {
                dataRow.eatCodeInput.onEndEdit.AddListener((value) => OnEatCodeChanged(rowIndex, value));
            }
            
            // 上报输入框事件 - 使用onEndEdit避免输入过程中频繁刷新
            if (dataRow.reportInput != null)
            {
                dataRow.reportInput.onEndEdit.AddListener((value) => OnReportChanged(rowIndex, value));
            }
        }
        
        #endregion
        
        #region 数据更新方法
        
        /// <summary>
        /// 更新列表项数据（系统更新）
        /// </summary>
        /// <param name="itemData">列表项数据（最多4个号码）</param>
        /// <param name="startIndex">起始索引</param>
        /// <param name="onBetDataFieldChanged">数据字段变化回调</param>
        /// <param name="isZodiacYear">是否为本命年特殊行</param>
        public void UpdateItemData(List<NumberBetData> itemData, int startIndex, Action<int, BetDataFieldType, float> onBetDataFieldChanged, bool isZodiacYear = false)
        {
            Debug.Log($"[C_Bet_ScrollViewItem] 更新项数据 - 起始索引: {startIndex}, 数据数量: {(itemData != null ? itemData.Count : 0)}");
            
            if (!m_IsInitialized)
            {
                Debug.Log("[C_Bet_ScrollViewItem] 未初始化，开始初始化...");
                Initialize();
            }
            
            // 设置系统更新标志位，确保整个数据更新过程不触发用户输入事件
            m_IsSystemUpdating = true;
            
            try
            {
                m_ItemData = itemData;
                m_StartIndex = startIndex;
                m_OnBetDataFieldChanged = onBetDataFieldChanged;
                
                if (itemData != null)
                {
                    for (int i = 0; i < itemData.Count; i++)
                    {
                        Debug.Log($"[C_Bet_ScrollViewItem] 数据[{i}]: 号码{itemData[i].number}, 总押注{itemData[i].totalBetAmount}");
                    }
                }
                
                // 处理本命年特殊显示
                if (isZodiacYear)
                {
                    UpdateZodiacYearDisplay();
                }
                else
                {
                    // 更新名称显示
                    UpdateNameDisplay();
                    
                    // 更新各个数据行
                    UpdateDataRows();
                }
            }
            finally
            {
                m_IsSystemUpdating = false;
            }
            
            Debug.Log("[C_Bet_ScrollViewItem] 项数据更新完成");
        }
        
        /// <summary>
        /// 更新名称显示
        /// </summary>
        private void UpdateNameDisplay()
        {
            if (m_SpecificNameText == null || m_ItemData == null || m_ItemData.Count == 0)
                return;
            
            // 获取第一个有效号码对应的属相
            foreach (var data in m_ItemData)
            {
                if (data.number > 0)
                {
                    string zodiac = ZodiacHelper.GetZodiacByNumber(data.number);
                    m_SpecificNameText.text = zodiac;
                    return;
                }
            }
            
            m_SpecificNameText.text = "";
        }

        /// <summary>
        /// 更新本命年特殊显示
        /// </summary>
        private void UpdateZodiacYearDisplay()
        {
            Debug.Log("[C_Bet_ScrollViewItem] 更新本命年特殊显示");
            
            // 显示本命年文本
            if (m_SpecificNameText != null)
            {
                m_SpecificNameText.text = "本命年";
            }
            
            // 查找并显示ZodiacYearSpacer节点
            Transform zodiacYearSpacer = transform.Find("BetData_Content/ZodiacYearSpacer");
            if (zodiacYearSpacer != null)
            {
                zodiacYearSpacer.gameObject.SetActive(true);
                Debug.Log("[C_Bet_ScrollViewItem] 显示ZodiacYearSpacer节点");
            }
            
            // 查找并显示ZodiacYearNumber_Info节点
            Transform zodiacYearNumberInfo = transform.Find("BetData_Content/ZodiacYearNumber_Info");
            if (zodiacYearNumberInfo != null)
            {
                zodiacYearNumberInfo.gameObject.SetActive(true);
                Debug.Log("[C_Bet_ScrollViewItem] 显示ZodiacYearNumber_Info节点");
                
                // 更新49号数据
                if (m_ItemData != null && m_ItemData.Count > 0)
                {
                    UpdateZodiacYearNumberData(zodiacYearNumberInfo, m_ItemData[0]);
                }
            }
            
            // 隐藏普通的数据行
            HideNormalDataRows();
        }

        /// <summary>
        /// 更新本命年49号数据显示
        /// </summary>
        /// <param name="zodiacYearNode">本命年节点</param>
        /// <param name="betData">49号押注数据</param>
        private void UpdateZodiacYearNumberData(Transform zodiacYearNode, NumberBetData betData)
        {
            // 查找49号码显示
            Transform numberText = zodiacYearNode.Find("Data_Row_1/Number_Background/Number");
            if (numberText != null)
            {
                var textComponent = numberText.GetComponent<TextMeshProUGUI>();
                if (textComponent != null)
                {
                    textComponent.text = betData.number.ToString("D2"); // 显示49
                }
            }
            
            // 查找并更新输入框（不触发事件）
            Transform totalBetInput = zodiacYearNode.Find("Data_Row_1/Total_Bet_Input_Background/Row1_Total_Bet_Input");
            if (totalBetInput != null)
            {
                var inputComponent = totalBetInput.GetComponent<TMP_InputField>();
                if (inputComponent != null)
                {
                    UpdateZodiacYearInputFieldValue(inputComponent, betData.totalBetAmount);
                    // 绑定本命年总押注输入事件
                    BindZodiacYearInputEvent(inputComponent, BetDataFieldType.TotalBet);
                }
            }
            
            Transform eatCodeInput = zodiacYearNode.Find("Data_Row_1/Eat_Code_Input_Background/Row1_Total_Bet_Input");
            if (eatCodeInput != null)
            {
                var inputComponent = eatCodeInput.GetComponent<TMP_InputField>();
                if (inputComponent != null)
                {
                    UpdateZodiacYearEatCodeInputFieldValue(inputComponent, betData.selfBetAmount);
                    // 绑定本命年吃码输入事件
                    BindZodiacYearInputEvent(inputComponent, BetDataFieldType.EatCode);
                }
            }
            
            Transform reportInput = zodiacYearNode.Find("Data_Row_1/Report_Input_Background/Row1_Total_Bet_Input");
            if (reportInput != null)
            {
                var inputComponent = reportInput.GetComponent<TMP_InputField>();
                if (inputComponent != null)
                {
                    UpdateZodiacYearInputFieldValue(inputComponent, betData.reportAmount);
                    // 绑定本命年上报输入事件
                    BindZodiacYearInputEvent(inputComponent, BetDataFieldType.Report);
                }
            }
            
            Debug.Log($"[C_Bet_ScrollViewItem] 更新本命年49号数据: 总押注{betData.totalBetAmount}, 吃码{betData.selfBetAmount}, 上报{betData.reportAmount}");
        }
        
        /// <summary>
        /// 更新本命年输入框数值（系统设置值，不触发用户输入事件）
        /// 使用标志位来区分系统更新和用户输入，保持监听器完整性
        /// </summary>
        /// <param name="inputField">输入框</param>
        /// <param name="value">数值</param>
        private void UpdateZodiacYearInputFieldValue(TMP_InputField inputField, float value)
        {
            if (inputField == null) return;
            
            // 设置系统更新标志位
            m_IsSystemUpdating = true;
            
            try
            {
                // 设置数值，如果是0则显示"0"，否则显示带小数点的格式
                if (value == 0)
                {
                    inputField.text = "0";
                }
                else
                {
                    inputField.text = value.ToString("0.##");
                }
            }
            finally
            {
                // 确保标志位被重置
                m_IsSystemUpdating = false;
            }
        }

        /// <summary>
        /// 更新本命年吃码输入框数值（不触发事件，显示为整数）
        /// </summary>
        /// <param name="inputField">输入框</param>
        /// <param name="value">数值</param>
        private void UpdateZodiacYearEatCodeInputFieldValue(TMP_InputField inputField, float value)
        {
            if (inputField == null) return;
            
            // 设置系统更新标志位
            m_IsSystemUpdating = true;
            
            try
            {
                // 本命年吃码数量显示为整数
                inputField.text = Mathf.FloorToInt(value).ToString();
            }
            finally
            {
                // 确保标志位被重置
                m_IsSystemUpdating = false;
            }
        }

        /// <summary>
        /// 绑定本命年输入框事件
        /// </summary>
        /// <param name="inputField">输入框</param>
        /// <param name="fieldType">字段类型</param>
        private void BindZodiacYearInputEvent(TMP_InputField inputField, BetDataFieldType fieldType)
        {
            if (inputField == null) return;
            
            // 先移除之前的监听器，避免重复绑定
            inputField.onEndEdit.RemoveAllListeners();
            
            // 绑定新的监听器 - 使用onEndEdit避免输入过程中频繁刷新
            inputField.onEndEdit.AddListener((value) => OnZodiacYearInputChanged(fieldType, value));
            
            Debug.Log($"[C_Bet_ScrollViewItem] 绑定本命年输入事件: {fieldType}");
        }

        /// <summary>
        /// 本命年输入框数值变化事件
        /// </summary>
        /// <param name="fieldType">字段类型</param>
        /// <param name="value">输入值</param>
        private void OnZodiacYearInputChanged(BetDataFieldType fieldType, string value)
        {
            // 如果是系统更新，忽略此事件
            if (m_IsSystemUpdating)
            {
                Debug.Log($"[C_Bet_ScrollViewItem] 系统更新中，忽略本命年输入变化事件 - 字段: {fieldType}");
                return;
            }
            
            Debug.Log($"[C_Bet_ScrollViewItem] 用户输入本命年数据变化 - 字段: {fieldType}, 输入值: {value}");
            
            // 本命年对应的是49号，数据在第0个位置
            if (m_ItemData == null || m_ItemData.Count == 0)
            {
                Debug.LogError("[C_Bet_ScrollViewItem] 本命年数据为空");
                return;
            }
            
            if (float.TryParse(value, out float inputValue))
            {
                var betData = m_ItemData[0]; // 49号数据
                
                // 通过回调精确通知上层：哪个号码的哪个字段被修改为什么值
                m_OnBetDataFieldChanged?.Invoke(betData.number, fieldType, inputValue);
                
                Debug.Log($"[C_Bet_ScrollViewItem] 本命年49号字段变化通知: 号码{betData.number}, 字段{fieldType}, 值{inputValue}");
            }
            else
            {
                Debug.LogWarning($"[C_Bet_ScrollViewItem] 本命年输入值解析失败: {value}");
            }
        }



        /// <summary>
        /// 隐藏普通数据行
        /// </summary>
        private void HideNormalDataRows()
        {
            foreach (var dataRow in m_DataRows)
            {
                SetDataRowVisible(dataRow, false);
            }
            
            // 隐藏普通的Number_Info节点
            for (int i = 1; i <= 4; i++)
            {
                Transform numberInfo = transform.Find($"BetData_Content/Number_Info_{i}");
                if (numberInfo != null)
                {
                    numberInfo.gameObject.SetActive(false);
                }
            }
        }
        
        /// <summary>
        /// 更新数据行显示
        /// </summary>
        private void UpdateDataRows()
        {
            Debug.Log($"[C_Bet_ScrollViewItem] 更新数据行 - 数据行数量: {m_DataRows.Count}, 数据数量: {(m_ItemData != null ? m_ItemData.Count : 0)}");
            
            // 隐藏本命年特殊节点
            HideZodiacYearNodes();
            
            // 显示普通的Number_Info节点
            for (int i = 1; i <= 4; i++)
            {
                Transform numberInfo = transform.Find($"BetData_Content/Number_Info_{i}");
                if (numberInfo != null)
                {
                    numberInfo.gameObject.SetActive(true);
                }
            }
            
            for (int i = 0; i < m_DataRows.Count; i++)
            {
                NumberDataRow dataRow = m_DataRows[i];
                
                if (m_ItemData != null && i < m_ItemData.Count && m_ItemData[i].number >= 0)
                {
                    // 有效数据，显示数据行
                    NumberBetData betData = m_ItemData[i];
                    dataRow.dataIndex = m_StartIndex + i;
                    
                    Debug.Log($"[C_Bet_ScrollViewItem] 更新数据行{i}: 号码{betData.number}, 总押注{betData.totalBetAmount}");
                    
                    UpdateDataRowDisplay(dataRow, betData);
                    SetDataRowVisible(dataRow, true);
                }
                else
                {
                    // 无效数据，隐藏数据行
                    Debug.Log($"[C_Bet_ScrollViewItem] 隐藏数据行{i}");
                    dataRow.dataIndex = -1;
                    SetDataRowVisible(dataRow, false);
                }
            }
        }

        /// <summary>
        /// 隐藏本命年特殊节点
        /// </summary>
        private void HideZodiacYearNodes()
        {
            // 隐藏ZodiacYearSpacer节点
            Transform zodiacYearSpacer = transform.Find("BetData_Content/ZodiacYearSpacer");
            if (zodiacYearSpacer != null)
            {
                zodiacYearSpacer.gameObject.SetActive(false);
            }
            
            // 隐藏ZodiacYearNumber_Info节点
            Transform zodiacYearNumberInfo = transform.Find("BetData_Content/ZodiacYearNumber_Info");
            if (zodiacYearNumberInfo != null)
            {
                zodiacYearNumberInfo.gameObject.SetActive(false);
            }
        }
        
        /// <summary>
        /// 更新单个数据行显示
        /// </summary>
        /// <param name="dataRow">数据行</param>
        /// <param name="betData">押注数据</param>
        private void UpdateDataRowDisplay(NumberDataRow dataRow, NumberBetData betData)
        {
            // 更新第一列显示号码（格式化为两位数）
            if (dataRow.numberText != null)
            {
                dataRow.numberText.text = betData.number.ToString("D2");
            }
             
            // 更新输入框数值（不触发事件）
            UpdateInputFieldValue(dataRow.totalBetInput, betData.totalBetAmount);
            UpdateEatCodeInputFieldValue(dataRow.eatCodeInput, betData.selfBetAmount);
            UpdateInputFieldValue(dataRow.reportInput, betData.reportAmount);
        }
        
        /// <summary>
        /// 更新输入框数值（系统设置值，不触发用户输入事件）
        /// 使用标志位来区分系统更新和用户输入，更加稳定可靠
        /// </summary>
        /// <param name="inputField">输入框</param>
        /// <param name="value">数值</param>
        private void UpdateInputFieldValue(TMP_InputField inputField, float value)
        {
            if (inputField == null) return;
            
            // 设置系统更新标志位
            m_IsSystemUpdating = true;
            
            try
            {
                // 设置数值，如果是0则显示"0"，否则显示带小数点的格式
                if (value == 0)
                {
                    inputField.text = "0";
                }
                else
                {
                    inputField.text = value.ToString("0.##");
                }
            }
            finally
            {
                // 确保标志位被重置，即使出现异常也能恢复
                m_IsSystemUpdating = false;
            }
        }

        /// <summary>
        /// 更新吃码输入框数值（不触发事件，显示为整数）
        /// </summary>
        /// <param name="inputField">输入框</param>
        /// <param name="value">数值</param>
        private void UpdateEatCodeInputFieldValue(TMP_InputField inputField, float value)
        {
            if (inputField == null) return;
            
            // 设置系统更新标志位
            m_IsSystemUpdating = true;
            
            try
            {
                // 吃码数量显示为整数
                inputField.text = Mathf.FloorToInt(value).ToString();
            }
            finally
            {
                // 确保标志位被重置，即使出现异常也能恢复
                m_IsSystemUpdating = false;
            }
        }
        
        /// <summary>
        /// 设置数据行可见性
        /// </summary>
        /// <param name="dataRow">数据行</param>
        /// <param name="visible">是否可见</param>
        private void SetDataRowVisible(NumberDataRow dataRow, bool visible)
        {
            if (dataRow.numberBackground != null)
                dataRow.numberBackground.SetActive(visible);
            if (dataRow.totalBetBackground != null)
                dataRow.totalBetBackground.SetActive(visible);
            if (dataRow.eatCodeBackground != null)
                dataRow.eatCodeBackground.SetActive(visible);
            if (dataRow.reportBackground != null)
                dataRow.reportBackground.SetActive(visible);
        }
        
        #endregion
        
        #region 输入事件处理
        
        /// <summary>
        /// 总押注数值变化事件
        /// </summary>
        /// <param name="rowIndex">行索引</param>
        /// <param name="value">输入值</param>
        private void OnTotalBetChanged(int rowIndex, string value)
        {
            // 如果是系统更新，忽略此事件
            if (m_IsSystemUpdating)
            {
                Debug.Log($"[C_Bet_ScrollViewItem] 系统更新中，忽略总押注变化事件 - 行索引: {rowIndex}");
                return;
            }
            
            Debug.Log($"[C_Bet_ScrollViewItem] 用户输入总押注变化 - 行索引: {rowIndex}, 输入值: {value}");
            if (rowIndex < 0 || rowIndex >= m_ItemData.Count)
            {
                return;
            }
            
                         if (float.TryParse(value, out float totalBet))
             {
                 var betData = m_ItemData[rowIndex];
                 
                 // 通过回调精确通知上层：哪个号码的哪个字段被修改为什么值
                 m_OnBetDataFieldChanged?.Invoke(betData.number, BetDataFieldType.TotalBet, totalBet);
                 
                 Debug.Log($"[C_Bet_ScrollViewItem] 总押注字段变化通知: 号码{betData.number}, 字段TotalBet, 值{totalBet}");
             }
        }
        
        /// <summary>
        /// 吃码数值变化事件
        /// </summary>
        /// <param name="rowIndex">行索引</param>
        /// <param name="value">输入值</param>
        private void OnEatCodeChanged(int rowIndex, string value)
        {
            // 如果是系统更新，忽略此事件
            if (m_IsSystemUpdating)
            {
                Debug.Log($"[C_Bet_ScrollViewItem] 系统更新中，忽略吃码变化事件 - 行索引: {rowIndex}");
                return;
            }
            
            Debug.Log($"[C_Bet_ScrollViewItem] 用户输入吃码变化 - 行索引: {rowIndex}, 输入值: {value}");
            if (rowIndex < 0 || rowIndex >= m_ItemData.Count) return;
            
                         if (float.TryParse(value, out float eatCode))
             {
                 var betData = m_ItemData[rowIndex];
                 
                 // 通过回调精确通知上层：哪个号码的哪个字段被修改为什么值
                 m_OnBetDataFieldChanged?.Invoke(betData.number, BetDataFieldType.EatCode, eatCode);
                 
                 Debug.Log($"[C_Bet_ScrollViewItem] 吃码字段变化通知: 号码{betData.number}, 字段EatCode, 值{eatCode}");
             }
        }
        
        /// <summary>
        /// 上报数值变化事件
        /// </summary>
        /// <param name="rowIndex">行索引</param>
        /// <param name="value">输入值</param>
        private void OnReportChanged(int rowIndex, string value)
        {
            // 如果是系统更新，忽略此事件
            if (m_IsSystemUpdating)
            {
                Debug.Log($"[C_Bet_ScrollViewItem] 系统更新中，忽略上报变化事件 - 行索引: {rowIndex}");
                return;
            }
            
            Debug.Log($"[C_Bet_ScrollViewItem] 用户输入上报变化 - 行索引: {rowIndex}, 输入值: {value}");
            if (rowIndex < 0 || rowIndex >= m_ItemData.Count) return;
            
                         if (float.TryParse(value, out float reportAmount))
             {
                 var betData = m_ItemData[rowIndex];
                 
                 // 通过回调精确通知上层：哪个号码的哪个字段被修改为什么值
                 m_OnBetDataFieldChanged?.Invoke(betData.number, BetDataFieldType.Report, reportAmount);
                 
                 Debug.Log($"[C_Bet_ScrollViewItem] 上报字段变化通知: 号码{betData.number}, 字段Report, 值{reportAmount}");
             }
        }
        
        #endregion
        
        #region 公共接口方法
        
        /// <summary>
        /// 获取指定行的押注数据
        /// </summary>
        /// <param name="rowIndex">行索引</param>
        /// <returns>押注数据</returns>
        public NumberBetData GetRowBetData(int rowIndex)
        {
            if (m_ItemData == null || rowIndex < 0 || rowIndex >= m_ItemData.Count)
                return new NumberBetData(-1); // 提供默认参数
            
            return m_ItemData[rowIndex];
        }
        
        /// <summary>
        /// 设置指定行的押注数据（系统更新）
        /// </summary>
        /// <param name="rowIndex">行索引</param>
        /// <param name="betData">押注数据</param>
        public void SetRowBetData(int rowIndex, NumberBetData betData)
        {
            if (m_ItemData == null || rowIndex < 0 || rowIndex >= m_ItemData.Count)
                return;
            
            // 设置系统更新标志位，确保整个更新过程不触发用户输入事件
            m_IsSystemUpdating = true;
            
            try
            {
                m_ItemData[rowIndex] = betData;
                
                // 更新对应行的显示
                if (rowIndex < m_DataRows.Count)
                {
                    UpdateDataRowDisplay(m_DataRows[rowIndex], betData);
                }
            }
            finally
            {
                m_IsSystemUpdating = false;
            }
        }
        
        /// <summary>
        /// 清空所有输入数据（系统操作）
        /// </summary>
        public void ClearAllInputs()
        {
            if (m_ItemData == null) return;
            
            // 设置系统更新标志位，确保清空操作不触发用户输入事件
            m_IsSystemUpdating = true;
            
            try
            {
                             for (int i = 0; i < m_ItemData.Count; i++)
                 {
                     var betData = m_ItemData[i];
                     betData.totalBetAmount = 0;
                     betData.selfBetAmount = 0;
                     betData.reportAmount = 0;
                     betData.riskValue = 0;
                     m_ItemData[i] = betData;
                 }
                
                // 刷新显示
                UpdateDataRows();
            }
            finally
            {
                m_IsSystemUpdating = false;
            }
        }
        
        /// <summary>
        /// 设置输入框可编辑状态
        /// </summary>
        /// <param name="editable">是否可编辑</param>
        public void SetInputsEditable(bool editable)
        {
            foreach (var dataRow in m_DataRows)
            {
                if (dataRow.totalBetInput != null)
                    dataRow.totalBetInput.interactable = editable;
                if (dataRow.eatCodeInput != null)
                    dataRow.eatCodeInput.interactable = editable;
                if (dataRow.reportInput != null)
                    dataRow.reportInput.interactable = editable;
            }
        }
        
        /// <summary>
        /// 获取当前项的数据范围
        /// </summary>
        /// <returns>起始索引和数据数量</returns>
        public (int startIndex, int count) GetDataRange()
        {
            return (m_StartIndex, m_ItemData?.Count ?? 0);
        }
        
        #endregion
        
        #region Unity生命周期
        
        private void Awake()
        {
            // 在Awake中进行基础查找
            FindComponents();
        }
        
        private void OnDestroy()
        {
            // 清理事件监听
            foreach (var dataRow in m_DataRows)
            {
                if (dataRow.totalBetInput != null)
                    dataRow.totalBetInput.onEndEdit.RemoveAllListeners();
                if (dataRow.eatCodeInput != null)
                    dataRow.eatCodeInput.onEndEdit.RemoveAllListeners();
                if (dataRow.reportInput != null)
                    dataRow.reportInput.onEndEdit.RemoveAllListeners();
            }
            
            m_OnBetDataFieldChanged = null;
            m_ItemData = null;
        }
        
        #endregion
    }
} 